#include "ZipManager.h"
#include "ZipValidator.h"
#include "ZipDecompressor.h"
#include "Util.h"
#include "FileUtils.h"
#include "ZipCompressor.h"

int ZipNavigator::maxFileNameLength_;

std::string ZipDecompressor::output_;

ZipManager::ZipManager()
{
    this->validator_ = new ZipValidator();
    this->zipReader_ = 0;
}

ZipManager::~ZipManager()
{
    if(this->validator_)
        delete this->validator_;
    if(this->zipReader_)
    {
        delete this->zipReader_;
        cleanupList(this->fileHeaderList_);
    }
}

void ZipManager::openFile(const char* fileName)
{

    if(validator_->validateZip(fileName) == VALID_ZIP_FILE)
    {
        if(this->zipReader_)
        {
            delete this->zipReader_;
            cleanupList(this->fileHeaderList_);
        }

        this->zipReader_ = new ZipReader(fileName);
        this->fileHeaderList_ = zipReader_->extractFileHeaders();
    }
}

void ZipManager::traverse(PF_Traverse pfTraverse)
{
    std::list<FileHeader*>::iterator headersList = this->fileHeaderList_.begin();
    for(; headersList != this->fileHeaderList_.end(); headersList++)
        pfTraverse(*headersList);
}

void ZipManager::decompress(const char* output)
{
    ZipDecompressor::output_ = appendSlash(output);
    traverse(ZipDecompressor::decompress);
}

void ZipManager::compress(const char* fileName, const char* output, std::vector<std::string> pathList)
{
    ZipCompressor compressor;
    compressor.compress(pathList, output, fileName);
}

void ZipManager::navigate()
{
    ZipNavigator::maxFileNameLength_ = 0;
    this->traverse(ZipNavigator::calculateMaxFileNameLength);
    this->traverse(ZipNavigator::navigateFunction);
}